package com.lenovo.smarttraffic.zm;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpUtils1 {
    public static String TAG = "OkHttpUtils1  Result";
    public static OkHttpClient client = new OkHttpClient.Builder()
            .readTimeout(1, TimeUnit.SECONDS)
            .connectTimeout(1, TimeUnit.SECONDS)
            .build();

    public static MediaType JSON = MediaType.parse("application/json,charset=UTF-8");

    public interface OnResLis {
        void success(String result);
    }

    public static String answer;


    //子线程调用handler  需要手动调用looper
    public static Handler handler = new Handler(Looper.getMainLooper());

    public static String post(String url, String json) {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try {

            Response response = client.newCall(request).execute();

            if (response.isSuccessful()) {
                answer = response.body().string();
            } else {
                //如果请求失败
                //之前的answer 不会被刷新
                answer = null;
                String TAG = "OK_HTTP_UTILS  请求失败   ";
                //   answer="";
                Log.e(TAG, "    ");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return answer;
    }

    //实体类中调用
    public static void doRequest(final String url, final String json, final OnResLis lis) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                //将之前的内容清掉
                answer=null;
                answer = post(url, json);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        lis.success(answer);
                    }
                });
            }
        }).start();
    }





}
